<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>4-3利用watch实现书籍实时检索</title>
    <script src="https://unpkg.com/vue@3"></script>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="app">
        <div>
            <label>按编号查询书籍：</label><input type="text" v-model.number="searchid" />
        </div>
        <table>
            <thead>
                <tr>
                    <th>序号</th>
                    <th>书籍名称</th>
                    <th>出版日期</th>
                    <th>价格</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="item in res">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.date}}</td>
                    <td>{{'￥'+item.price.toFixed(2)}}</td>

                </tr>
            </tbody>
        </table>
    </div>
    <script>
        const { createApp } = Vue;
        createApp({
            data() {
                return {
                    searchid: 0,
                    res: [],
                    books: [
                        { id: 1, name: "《JavaScript程序设计》", date: "2022-9", price: 85.00, num: 1 },
                        { id: 2, name: "《C语言基础》", date: "2021-2", price: 59.00, num: 1 },
                        { id: 3, name: "《Java高级语言编程》", date: "2022-10", price: 39.00, num: 1 },
                        { id: 4, name: "《数据库原理》", date: "2023-3", price: 128.00, num: 1 },
                        { id: 5, name: "《计算机网络》", date: "2022-8", price: 88.00, num: 1 },
                    ],
                };
            },
            watch: {
                searchid(newValue, oldValue) {
                    if (newValue != oldValue) {
                        this.res = this.books.filter(function (item) {
                            return item.id == newValue;
                        })
                    }
                }
            }
        }).mount("#app");
    </script>
</body>

</html>